package com.niit.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class KafkaProducerParameters {

    public static void main(String[] args) {
        //1.配置
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"node1:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());

        props.put(ProducerConfig.ACKS_CONFIG,"all");
        //重试次数 默认 int 最大是 2147483647
        props.put(ProducerConfig.RETRIES_CONFIG,3);
        //开启幂等性有序设置为 小于等于5 不开启幂等性 就直接为1 
        props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION,4);

        //缓冲区的大小                                    32M
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG,33554432);
        //批次大小                                     16K
        props.put(ProducerConfig.BATCH_SIZE_CONFIG,16384);
        //等到时间 ms
        props.put(ProducerConfig.LINGER_MS_CONFIG,1);
        //压缩
        props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");

        //使用自定义分区策略
        props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,MyPartitioner.class.getName());

        //2.创建生产者
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(props);
        //3.发送数据
        for (int i = 0; i<1000;i++){
            ProducerRecord<String,String> record = new ProducerRecord<>("BD2_1","BD2_"+i);
            producer.send(record);
        }
        //4.关闭资源
        producer.close();
    }

}
